package com.sdtele.tta.operation;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonElement;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.User;
import com.sdtele.tta.utils.TeamUtils;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationChgUser extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");

		if (curUser != null) {
			long userId = jsonRequest.getJsonObject().get("userId").getAsLong();
			User user = Dac.getInstance().getUser(userId);

			String phone = jsonRequest.getJsonObject().get("phone").getAsString();
			String email = jsonRequest.getJsonObject().get("email").getAsString();
			String sex = jsonRequest.getJsonObject().get("sex").getAsString();
			String avatar = jsonRequest.getJsonObject().get("avatar").getAsString();
			String name = jsonRequest.getJsonObject().get("name").getAsString();
			Long teamId = jsonRequest.getJsonObject().get("teamId").getAsLong();
			int isManager = jsonRequest.getJsonObject().get("isManager").getAsInt();

			if (user.getAccount().equals(curUser.getAccount())) {
				if (name.isEmpty()) {
					jres.setStatus(1);
					jres.setMessage("姓名不能为空");
					return jres;
				}
			} else {
				if (curUser.getIsManager() == 1) {
					Set<Long> teamIdSet = new HashSet<Long>();
					teamIdSet.add(curUser.getTeamId());
					TeamUtils.teamAuthority(curUser.getTeamId(), teamIdSet);
					if (!teamIdSet.contains(teamId)) {
						jres.setStatus(1);
						jres.setMessage("您的管理权限不够修改该员工信息");
						return jres;
					} else {
						if (name.isEmpty()) {
							jres.setStatus(1);
							jres.setMessage("姓名不能为空");
							return jres;
						}
						if (teamId.equals(null)) {
							jres.setStatus(1);
							jres.setMessage("组织机构不能为空");
							return jres;
						}
					}
				} else {
					jres.setStatus(1);
					jres.setMessage("您不是管理员，不能修改其他人的个人信息");
					return jres;
				}
			}			
			user.setName(name);
			user.setTeamId(teamId);
			user.setIsManager(isManager);
			user.setPhone(phone);
			user.setEmail(email);
			user.setSex(sex);
			user.setAvatar(avatar);
			if (Dac.getInstance().chgUser(user)) {
				jres.setStatus(0);
				jres.setMessage("修改用户成功");
				jres.setEntity(user);
			} else {
				jres.setStatus(1);
				jres.setMessage("修改用户失败");
			}
		} else {
			jres.setStatus(1);
			jres.setMessage("用户未登录");
		}
		return jres;
	}

}
